package servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/code")
public class checkcodeServlewt extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*1.创建一个图片对象，验证码图片对象，把它加载到内存*/
        int height=50;
        int width=100;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        /*2.美化图片*/
/*2.1填充背景颜色*/
        /*画笔对象*/

        Graphics graphics = image.getGraphics();/*获取画笔对象*/
        graphics.setColor(Color.PINK);/*设置画笔颜色*/
        graphics.fillRect(0,0,width,height);/*填充颜色 具体颜色有setColor*/
        graphics.setColor(Color.red);
        graphics.drawRect(0,0,width-1,height-1);/*画边框，边框*/
        /*2.3画验证码*/
        graphics.setColor(Color.CYAN);
        String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random ran=new Random();
        StringBuilder sbuilder=new StringBuilder();
        for (int i=0;i<4;i++){
            graphics.setFont(new Font("宋体",5,30));
            int index = ran.nextInt(str.length());
            char ch = str.charAt(index);
            sbuilder.append(ch);
            graphics.drawString(ch+"",width/5*i,height/2);
        }
        String checkCode_session = sbuilder.toString();
        /*将验证码存入session中*/
        req.getSession().setAttribute("checkCode_session",checkCode_session);
        graphics.setColor(Color.green);
        for(int i=0;i<10;i++){
            int x1=ran.nextInt(width);
            int x2= ran.nextInt(width);
            int y1=ran.nextInt(height);
            int y2=ran.nextInt(height);
            graphics.drawLine(x1,y1,x2,y2);
        }
//        graphics.drawLine(1,1,80,120);
//        graphics.drawLine(1,1,70,80);
//        graphics.drawLine(1,1,89,78);
//        graphics.drawLine(1,1,84,82);
//        graphics.drawString("A",20,25);
//        graphics.drawString("A",40,25);
//        graphics.drawString("A",60,25);
//        graphics.drawString("A",80,25);
        /*将图片输出到页面展示 将内存中的图片以jpg格式输出到页面上*/
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
}
